var app = getApp()
const baseUrl = app.globalData.baseUrl;
Page({
  data: {
    showIndex: 0, //顶部选项卡索引
    // 推荐
    recommend: {
      "group": '限时团购',
      "flashSale": '  FLASH SALE',
      "newgoods": '新品',
      'newArrival': '  NEW ARRIVAL',
      'hotbuy': '热卖专区',
      'hotSale': '  HOT SALE'
    },
    collectproduct: [],
    productList: [],
    countDownList: [],
    actEndTimeList: [],
    swiperCurrent: 0,
    newCurrent: 0,
    categorieswiper: [{id:2,title:"推荐"}],
    categoriesList: [],
    groupList: [],
    showAuth: false
  },

  onLoad: function () {
    //---------categories---------
    var that = this;
    var url = baseUrl + '/yq/item/categories';
    var params = {};
    var success = res => {
      that.setData({
        categoriesList: res.info,
        categorieswiper: this.data.categorieswiper.concat(res.info)
      })
    //  console.log("分类调用成功：", res);
    //  console.log("分类调用成功2：", this.data.categorieswiper);
      //---------调用banners------
      this.banners();
      //--------model-------
      this.model();
      //---------group------------
      this.group();
      //----------hotProducts-----
      this.hotProducts();
      //----------newProducts-----
      this.newProducts();
    }
    var fail = res => { }
    app.request(url, params, success, fail);
    //----------openId------------
    wx.getStorage({
      key: 'openId',
      success(res) {
        console.log("openId:" + res.data)
      }
    })
  },
  onShow: function() {
    if (this.data.showIndex != 0) {
      console.log(this.data.categoriesList[this.data.showIndex - 1]);
      var that = this;
      var productUrl = baseUrl + '/yq/product/list';
      var params = {
        categoryId: this.data.categoriesList[this.data.showIndex - 1].id,
      }
      var success = res => {
        that.setData({
          productList: res.info
        })
       // console.log("商品列表：", res)
      }
      var fail = res => {
        console.log(res)
        console.log("商品列表失败")
      }
      app.request(productUrl, params, success, fail);
    }
    this.init();
  },
  init() {
    // if (this.data.showAuth==true)
    var that = this;
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // var url = baseUrl + '/yq/user';
          // var params = {};
          // var success = function (res) {
          //   that.setData({
          //     userInfo: res.info
          //   })
          //   console.log(res.info);
          // };
          // var fail = function (res) { };
          // var complete = function () { };
          // app.request(url, params, success, fail, complete);

        } else {
          wx.setStorageSync("path", "pages/register/register");
          that.setData({
            showAuth: true
          })
          //隐藏系统tabbar
          wx.hideTabBar();
        }
      }
    })
  },

  //模块
  model:function(){
    var that = this;
    var url = baseUrl + '/yq/model?modelId=1';
    var params = {};
    var success = res => {
      that.setData({
        model: res.info.list,

      })
      console.log("model:", res);
    }
    var fail = res => { }
    app.request(url, params, success, fail);
  },
  //限时团购
  group: function () {
    var that = this;
    var url = baseUrl + '/yq/item/groups';
    var params = {};
    var success = res => {
      that.setData({
        groupList: res.info,

      })
      console.log("groupList", res);
      //-----调用倒计时
      this.countDowns(this.data.groupList);
    }
    var fail = res => { }
    app.request(url, params, success, fail);
  },
  //热买专区
  hotProducts: function () {
    var that = this;
    var url = baseUrl + '/yq/product/hotProducts';
    var params = {};
    var success = res => {
      that.setData({
        hotProductsList: res.info,
      })
    //  console.log("hotProductsList调用成功：", res);
    }
    var fail = res => { }
    app.request(url, params, success, fail);
  },
  // 轮播图
  banners: function () {
    var that = this
    var url = baseUrl + '/yq/item/banners';
    var params = {};
    var success = res => {
      that.setData({
        bannersList: res.info,
      })
   //   console.log("banners调用成功：", res);
    }
    var fail = res => { }
    app.request(url, params, success, fail);
  },
  //新品推荐
  newProducts: function () {
    var that = this;
    var url = baseUrl + '/yq/product/newProducts';
    var params = {};
    var success = res => {
      that.setData({
        newProducts: res.info,
      })
     // console.log("newProducts调用成功：", res);
    }
    var fail = res => { }
    app.request(url, params, success, fail);
  },
  swiperChange: function (e) {

    this.setData({

      swiperCurrent: e.detail.current // current 改变时会触发 change 事件

    })
  },
  newChange: function (e) {

    this.setData({

      newCurrent: e.detail.current // current 改变时会触发 change 事件

    })
  },
  setTab: function (res) {
    this.setData({
      showIndex: res.currentTarget.dataset.tabindex,
    })
    var that = this;
    var productUrl = baseUrl + '/yq/product/list';
    if (this.data.showIndex != 0) {
    var  categoryId=this.data.categoriesList[this.data.showIndex - 1].id;
    }else{
      categoryId=1
    }
    var params = {
      categoryId: categoryId
    }
    var success = res => {
      that.setData({
        productList: res.info
      })
      console.log("商品列表：", res)
    }
    var fail = res => {
      console.log(res)
      console.log("商品列表失败")
    }
    app.request(productUrl, params, success, fail);
  },
  //收藏按钮
  collectbtn: function (e) {
    var that = this;
    const index = e.currentTarget.dataset.idx;
    let productList = this.data.productList;
    const isSubscribe = productList[index].isSubscribe;
    productList[index].isSubscribe = !isSubscribe;

    that.setData({
      productList: productList,
    })
    if (!isSubscribe) {
      var collectUrl = baseUrl + '/yq/user/subscribe';
      var params = {
        productId: this.data.productList[e.currentTarget.dataset.idx].id
      }
      var success = res => {
        console.log("收藏成功：", res)
      }
      var fail = res => {
        console.log(res)
        console.log("收藏失败")
      }
      app.request(collectUrl, params, success, fail);
    }
    else {
      var collectUrl = baseUrl + '/yq/user/unsubscribe';
      var params = {
        productId: this.data.productList[e.currentTarget.dataset.idx].id
      }
      var success = res => {
        console.log("取消收藏成功：", res)

      }
      var fail = res => {
        console.log(res)
        console.log("取消收藏失败")
      }
      app.request(collectUrl, params, success, fail);
    }
  },
  countDowns: function (options) {
    //-----------倒计时---------
    let endTimeList = [];
    // 将活动的结束时间参数提成一个单独的数组，方便操作
    options.forEach(o => {
      endTimeList.push(o.endTime)
    })
    this.setData({
      actEndTimeList: endTimeList
    });
    // 执行倒计时函数
    this.countDown();
  },
  timeFormat(param) { //小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown() { //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.actEndTimeList;
    let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = new Date(o).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
      } else { //活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
      }
      countDownArr.push(obj);
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      countDownList: countDownArr
    })
    setTimeout(this.countDown, 1000);
  }
  , togoods(e){
    if (!e.currentTarget.dataset.modelcid){ //没有分类id
      wx.navigateTo({
        url: '../goods/goods?id=' + e.currentTarget.dataset.modelid,
      })
    } else {
      var catId = e.currentTarget.dataset.modelcid;
      for (var i = 0; i < this.data.categorieswiper.length; i++) {
        if (Number(catId) === this.data.categorieswiper[i].id) {
          this.setData({
            showIndex: i
          })
          break;
        }
      }
      var that = this;
      var productUrl = baseUrl + '/yq/product/list';
      var params = {
        categoryId: this.data.categorieswiper[this.data.showIndex - 1].id,
      }
      var success = res => {
        that.setData({
          productList: res.info
        })
        console.log("商品列表：", res)
      }
      var fail = res => {
        console.log(res)
        console.log("商品列表失败")
      }
      app.request(productUrl, params, success, fail);
    }
  }
})